<template>
	<div class="items">
		<div class="item" v-for="(item,index) in items" :key="index" @click="$router.push({name:'Detail', params: {pid:item.pid}})">
			<img v-lazy="item.smallImg" :alt="item.name">
			<div class="item-info">
				<div class="name Text_abb">{{item.name}}</div>
				<div class="desc Text_abb">{{item.enname}}</div>
				<div class="price">
					￥{{item.price}}
					<van-icon 
						name="delete-o" 
						color="#999" 
						v-if="showDelete"
						@click.stop="removeLike(item.pid, index)" />
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import bus from '@/utils/eventBus.js'
	import { saveLike } from '@/api/detail.js'
	export default {
		props: {
			items: {
				type: Array,
				default () {
					return []
				}
			},
			showDelete: {
				type: Boolean,
				default: false
			}
		},
		methods: {
			// 删除某个收藏
			async removeLike (pid, index) {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$router.push({ name: "Login" })
				
				// 弹窗提示
				const resultConfirm = await this.$dialog.confirm({
					message: '是否移除收藏'
				}).catch(err => err)
				
				if (resultConfirm !== 'confirm') return this.$toast('取消操作')
				
				// 加载···
				this.$toast.loading({
					message: '删除中···',
					forbidClick: true
				})
				// 发起请求 第一个参数默认值为false（取消收藏）true为 (收藏)
				
				saveLike(status, {
					tokenString,
					pid
				})
				.then(({data: res}) => {
					console.log('移除收藏',res)
					if (res.code !== 900) return this.$toast.fail('请求异常,请重新尝试!')
					this.$toast.success(res.msg)
					// 通知：我删除了收藏
					bus.$emit('remove-like', index)
				})
				.catch(err => {
					this.$toast.fail('请求失败,请重新尝试!')
				})
				
			}
		}
	}
</script>

<style lang="scss" scoped>
	.items{
		display: flex;
		flex-wrap: wrap;
		row-gap: 10px;
		column-gap: 10px;
		.item{
			width: calc(100% / 3 - 10px + 10px / 3);
			img{
				width: 100%;
			}
			.item-info{
				margin-top: 10px;
				.name{
					font-size: 16px;
				}
				.desc{
					color: darkgray;
					font-size: 12px;
					margin: 5px 0;
				}
				.price{
					font-size: 16px;
					color: deepskyblue;
					font-weight: bold;
					display: flex;
					align-items: center;
					justify-content: space-between;
				}
			}
		}
	}
</style>